<template>
  <div v-loading="loading" class="AddOrUpdate_main add_container column_three">
    <div class="main_main">
      <el-form ref="form" :model="formData" :rules="rules" :inline="true">
        <el-form-item label="物料编码" class="clickChoose" prop="materialCode">
          <el-input v-model="formData.materialCode" placeholder="请选择" readonly />
          <a
            class="clickChoose_button"
            @click.prevent="chooseMaterial"
          >
            <svg-icon icon-class="选择弹框" />
          </a>
        </el-form-item>
        <el-form-item label="物料名称">
          <el-input v-model="formData.materialName" placeholder="暂无" disabled />
        </el-form-item>
        <el-form-item label="规格型号">
          <el-input v-model="formData.materialModel" placeholder="暂无" disabled />
        </el-form-item>
        <el-form-item label="物料分类">
          <el-input v-model="formData.materialTypeName" placeholder="暂无" disabled />
        </el-form-item>
        <el-form-item label="物料单位">
          <el-input v-model="formData.materialUnitName" placeholder="暂无" disabled />
        </el-form-item>
        <el-form-item label="备注" class="double">
          <el-input
            v-model="formData.remark"
            maxlength="200"
            show-word-limit
            type="textarea"
            placeholder="请输入"
          />
        </el-form-item>
        <el-form-item v-if="isShow" label="状态">
          <el-radio-group v-model="formData.status">
            <el-radio label="1">启用</el-radio>
            <el-radio label="0">停用</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <div class="formItem_header">
        价格信息
        <div class="formItem_header_operate">
          <a class="formItem_header_operate_item" @click="addRow">
            <svg-icon icon-class="新增" />
            <div class="item_name">添加</div>
          </a>
          <a class="formItem_header_operate_item delete" @click="deleteRow">
            <svg-icon icon-class="删除" />
            <div class="item_name">删除</div>
          </a>
        </div>
      </div>
      <div ref="table_container2" class="table_container draggableTable">
        <el-table
          ref="table"
          :data="listData"
          :height="tableHeight"
          stripe
          border
          style="width: 99.9%"
          :header-cell-class-name="headerCellClassName"
          @selection-change="selectionChange"
        >
          <el-table-column
            type="selection"
            width="70"
            align="center"
          />
          <el-table-column label="工序" min-width="180" prop="engineeringProcessId">
            <template slot-scope="scope">
              <el-select v-model="scope.row.engineeringProcessId" placeholder="请选择" @change="changeProcess(scope.row,scope.$index)">
                <el-option
                  v-for="item in workProcedureList"
                  :key="item.processId"
                  :label="item.engineeringProcessName"
                  :value="item.processId"
                />
              </el-select>
            </template>
          </el-table-column>
          <el-table-column label="外协供应商" min-width="180" prop="supplierName">
            <template slot-scope="scope">
              <el-input
                v-model="scope.row.supplierName"
                readonly
                placeholder="请选择"
                clearable
                @click.native="chooseSupplier(scope.row,scope.$index)"
              />
            </template>
          </el-table-column>
          <el-table-column label="含税单价" :min-width="SETTINGS.settings_decimalDigits_length" prop="taxPrice">
            <template slot-scope="scope">
              <el-input v-model="scope.row.taxPrice" placeholder="请输入" clearable />
            </template>
          </el-table-column>
          <el-table-column label="税率%" min-width="150" prop="taxRateLabel">
            <template slot-scope="scope">
              <el-select
                v-model="scope.row.taxRateCode"
                clearable
                filterable
                style="width:100%"
                placeholder="请选择"
              >
                <el-option
                  v-for="item in taxRateCodeList"
                  :key="item.dictCode"
                  :label="item.dictLabel"
                  :value="item.dictCode"
                />
              </el-select>
            </template>
          </el-table-column>
          <el-table-column v-if="id" label="查看" min-width="180">
            <template slot-scope="scope">

              <el-popover
                v-if="scope.row.id"
                :ref="`popover-`+scope.row.id"
                placement="left"
                width="700"
                trigger="click"
              >
                <el-button

                  slot="reference"
                  type="text"
                  @click.stop="adjustmentRecord(scope.row)"
                >调整记录</el-button>

                <div class="record">
                  <div class="all">
                    <div v-if="JSON.stringify(adjustmentList) !='[]'">
                      <div v-for="item in adjustmentList" :key="item.id" class="oneRecord">
                        <!-- <el-tooltip v-if="tipDisabled" class="item" effect="dark" :content="item.adjustContent" placement="top-start">
                              <span :ref="`domRecord${item.id}`">{{ item.adjustContent }}</span>
                            </el-tooltip> -->
                        <span :ref="`domRecord${item.id}`">{{ item.adjustContent }}</span>
                      </div>

                    </div>
                    <div v-else class="oneRecord">暂无数据</div>
                  </div>
                </div>
              </el-popover>
              <el-button
                v-else
                type="text"
                disabled
              >调整记录</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>
    <div class="main_bottom">
      <el-button type="cancel" @click.stop="cancel">取消</el-button>
      <el-button @click.stop="onSubmit">保存</el-button>
    </div>
  </div>
</template>

<script>
import { addOrUpdate, getInfo, getProcessInfoWithOutMaterialManage, adjust } from '@/api/outsourceManage/outsourcePrice'
import { list as workProcedure } from '@/api/engineeringManage/processManage'
import { list } from '@/api/purchaseManage/supplierInfo'
import { getDictSelects } from '@/api/common/common'
import chooseMaterial from './chooseMaterial'
import chooseSupplier from './chooseSupplier'
export default {
  name: 'AddOrUpdate',
  props: {
    layerid: {},
    id: {},
    defaultValue: {}
  },
  data() {
    return {
      loading: true,
      isShow: false,
      formData: {
        id: '',
        projectMaterialInformation: '',
        materialCode: '',
        materialName: '',
        materialModel: '',
        materialTypeName: '',
        materialUnitName: '',
        materialListVo: {},
        remark: '',
        data: [],
        status: '1'
      },
      pageData: {
        pageNum: 1,
        pageSize: 9999,
        orderByColumn: 'updateTime',
        isAsc: 'desc'
      },
      rowId: null,
      tableHeight: 265,
      workProcedureList: [],
      supplierData: [],
      selectionsAll: [],
      taxRateCodeList: [],
      peopleList: [],
      listData: [],
      selectionData: [],
      adjustmentList: [],
      rules: {
        materialCode: [
          { required: true, message: '物料编码不能为空', trigger: 'change' }
        ]
      }
    }
  },
  watch: {
    rowId: function(newValue, oldValue) {
      if (oldValue) {
        this.$refs[`popover-` + oldValue].doClose()
      }
    }
  },
  created() {
    if (!this.id) { // 没有id就是新增
      this.loading = false
    } else { // 有id就是编辑
      this.getInfo()
    }
    this.getList()
    this.getDictOptions()
  },
  methods: {
    adjustmentRecord(row) {
      this.rowId = row.id
      adjust(row.id).then(res => {
        this.adjustmentList = res.data
      })
    },
    headerCellClassName(data) {
      if (['engineeringProcessId', 'supplierName', 'taxPrice'].indexOf(data.column.property) != -1) {
        return 'column_bt'
      }
    },
    changeProcess(row, index) {
      const arr = this.$deepClone(this.listData)
      arr.splice(this.listData.indexOf(row), 1)
      if (arr.filter(item => item.engineeringProcessId && row.engineeringProcessId && item.outSupplierId && row.outSupplierId && item.outSupplierId == row.outSupplierId && item.engineeringProcessId == row.engineeringProcessId).length > 0) {
        this.listData[index].engineeringProcessId = ''
        this.$message.warning('该供应商下工序已存在,请重新选择工序')
      }
    },
    workProcedure() {
      getProcessInfoWithOutMaterialManage({ status: '1' }).then(res => {
        const arr = res.data.map(item => {
          return { processId: item.id, engineeringProcessName: item.name }
        })
        this.workProcedureList = Array.from(new Set(arr.map(JSON.stringify))).map(JSON.parse)
      })
    },

    getInfo() {
      getInfo(this.id).then(res => {
        this.formData = res.data
        this.listData = res.data.data
        this.isShow = true
        this.loading = false
        this.$set(this.formData, 'materialCode', res.data.materialListVo.materialCode)
        this.$set(this.formData, 'materialName', res.data.materialListVo.materialName)
        this.$set(this.formData, 'materialModel', res.data.materialListVo.materialModel)
        this.$set(this.formData, 'materialTypeName', res.data.materialListVo.materialTypeName)
        this.$set(this.formData, 'materialUnitName', res.data.materialListVo.materialUnitName)
        this.workProcedure()
      })
    },
    getList() {
      list(this.pageData).then(res => {
        this.peopleList = res.data
      })
    },
    getDictOptions() {
      getDictSelects('taxRateCode').then(res => {
        this.taxRateCodeList = res.data
      })
    },
    addRow() {
      if (this.formData.projectMaterialInformation) {
        const obj = {
          supplierName: '',
          outSupplierId: '',
          taxRateCode: '',
          taxPrice: '',
          engineeringProcessId: ''
        }
        this.listData.push(obj)
      } else {
        this.$message.warning('请选择物料编码')
        return
      }
    },
    selectionChange(row) {
      this.selectionsAll = row
    },
    deleteRow() {
      this.selectionsAll.forEach(item => {
        this.listData.splice(this.listData.indexOf(item), 1)
      })
    },
    showMaterial(data) {
      this.formData.projectMaterialInformation = data.id
      this.formData.materialCode = data.materialCode
      this.formData.materialName = data.materialName
      this.formData.materialModel = data.materialModel
      this.formData.materialTypeName = data.materialTypeName
      this.formData.materialUnitName = data.materialUnitName
      this.workProcedure()
    },
    chooseSupplier(row, index) {
      this.selectionData = []
      if (this.listData) {
        this.listData.forEach(item => {
          this.selectionData.push(item.outSupplierId)
        })
      }
      this.rowIndex = index
      this.$layer.iframe({// 弹框
        content: {
          content: chooseSupplier, // 传递的组件对象
          parent: this, // 当前的vue对象
          data: {
            id: row.outSupplierId ? row.outSupplierId : '',
            selectionData: this.selectionData

          }// props
        },
        area: ['880px', '700px'],
        title: '选择外协供应商', // 标题
        shadeClose: false // 点击遮罩是否关闭
      })
    },
    chooseMaterial() {
      this.$layer.iframe({
        // 弹框
        content: {
          content: chooseMaterial, // 传递的组件对象
          parent: this, // 当前的vue对象
          data: {
            id: this.formData.projectMaterialInformation ? this.formData.projectMaterialInformation : ''
          } // props
        },
        area: ['920px', '700px'],
        title: '选择物料', // 标题
        shadeClose: false // 点击遮罩是否关闭
      })
    },
    onSubmit() {
      this.$refs['form'].validate(valid => {
        if (valid) {
          if (this.listData.length <= 0) {
            this.$message.warning('请添加价格信息')
            return
          }
          if (this.listData.filter(item => !item.engineeringProcessId).length > 0) {
            this.$message.warning('工序不能为空')
            return
          } else if (this.listData.filter(item => !item.supplierName).length > 0) {
            this.$message.warning('外协供应商不能为空')
            return
          } else if (this.listData.filter(item => !item.taxPrice).length > 0) {
            this.$message.warning('含税单价不能为空')
            return
          } else if (this.listData.filter(item => item.taxPrice && !this.SETTINGS.reg_no_zero.test(item.taxPrice)).length > 0) {
            this.$message.warning('含税单价未正确填写')
            return
          }
          this.formData.data = this.listData
          addOrUpdate(this.formData).then(res => {
            this.$message({
              message: res.msg,
              type: 'success'
            })
            this.$layer.close(this.layerid) // 关闭弹框
            this.$parent.refresh() // 调用父组件的刷新方法
          })
        }
      })
    },

    cancel() {
      this.$layer.close(this.layerid)// 关闭弹框
    },
    addTypeCallBack(row) { // 设备类型弹窗关闭后赋值
      this.getAll()
      this.formData.typeId = row.id
      this.formData.typeName = row.name
    },
    showCustomer(data) {
      const arr = this.$deepClone(this.listData)
      const arr2 = this.$deepClone(this.listData)
      arr2.splice(this.listData.indexOf(arr[this.rowIndex]), 1)
      if (arr2.filter(item => item.engineeringProcessId && arr[this.rowIndex].engineeringProcessId && item.outSupplierId == data.id && item.engineeringProcessId == arr[this.rowIndex].engineeringProcessId).length > 0) {
        this.listData[this.rowIndex].outSupplierId = ''
        this.listData[this.rowIndex].supplierName = ''
        this.$message.warning('该供应商下工序已存在,请重新选择供应商')
        return
      } else {
        delete arr[this.rowIndex].id
        arr[this.rowIndex].outSupplierId = data.id
        arr[this.rowIndex].supplierName = data.name
        this.$set(arr[this.rowIndex], 'supplierName', data.name)
        this.listData = arr
      }
    },
    setFileName(...data) {
      this.formData.fileName = data[0]
      this.formData.fileRealName = data[1]
      this.formData.fileUrl = data[2]
    }
  }
}
</script>

<style lang="less" scoped>
.title {
  padding-left: 10px;
  padding-bottom: 20px;
  font-size: 24px;
  width: 100%;
}
.record_bottom {
  justify-content: space-between;
  h2 {
    flex: 1;
  }
}
.el-input{
  width: 100% !important;
}
/deep/.el-table__header {
  width: 100% !important;
}
/deep/ .el-table__body {
  width: 100% !important;
}
.record{
  max-height: 180px;
  overflow: auto;
  .all{
    border-left: 1px solid silver;
    padding-left: 10px;
    .oneRecord{
      margin: 10px 0;
      width: 650px;
      text-overflow: ellipsis;
      overflow: hidden;
      white-space: nowrap;
    }
  }
}
</style>
